<?php

namespace app\admin\controller\official;

use app\common\controller\Backend;
use app\admin\library\Auth;
use app\admin\model\official\OfficialConfig;
use fast\Tree;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use think\Loader;
use think\Session;

/**
 * 父级
 * Class BaseController
 * @package app\admin\controller
 */
class BaseController extends Backend
{

    /**
     * OfficialListProduct模型对象
     * @var \app\admin\model\official\OfficialListProduct
     */
    protected $model = null;
    protected $table_name = null;
    protected $OfficialCategoryModel = null;
    protected $categorylist = [];

    public function _initialize()
    {
        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;

        // 定义是否Addtabs请求
        !defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false);

        // 定义是否Dialog请求
        !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false);

        // 定义是否AJAX请求
        !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());

        // 检测IP是否允许
        check_ip_allowed();

        $this->auth = Auth::instance();

        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //检测是否登录
            if (!$this->auth->isLogin()) {
                Hook::listen('admin_nologin', $this);
                $url = Session::get('referer');
                $url = $url ? $url : $this->request->url();
                if (in_array($this->request->pathinfo(), ['/', 'index/index'])) {
                    $this->redirect('index/login', [], 302, ['referer' => $url]);
                    exit;
                }
                $this->error(__('Please login first'), url('index/login', ['url' => $url]));
            }

            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight)) {
                //查询当前管理员
                $au = $this->auth->getUserInfo();
                //不是超级管理员判断权限
                if (1 != $au['id']){
                    // 判断控制器和方法是否有对应权限
                    $pathinfo = str_replace('.', '/', $this->request->pathinfo());
                    if (!$this->auth->check([$path,$pathinfo])) {
                        Hook::listen('admin_nopermission', $this);
                        $this->error(__('You have no permission'), '');
                    }
                }
            }

        }

        // 非选项卡时重定向
        if (!$this->request->isPost() && !IS_AJAX && !IS_ADDTABS && !IS_DIALOG && input("ref") == 'addtabs') {
            $url = preg_replace_callback("/([\?|&]+)ref=addtabs(&?)/i", function ($matches) {
                return $matches[2] == '&' ? $matches[1] : '';
            }, $this->request->url());
            if (Config::get('url_domain_deploy')) {
                if (stripos($url, $this->request->server('SCRIPT_NAME')) === 0) {
                    $url = substr($url, strlen($this->request->server('SCRIPT_NAME')));
                }
                $url = url($url, '', false);
            }
            $this->redirect('index/index', [], 302, ['referer' => $url]);
            exit;
        }

        // 设置面包屑导航数据
        $breadcrumb = [];
        if (!IS_DIALOG && !config('fastadmin.multiplenav') && config('fastadmin.breadcrumb')) {
            $breadcrumb = $this->auth->getBreadCrumb($path);
            array_pop($breadcrumb);
        }
        $this->view->breadcrumb = $breadcrumb;

        // 如果有使用模板布局
        if ($this->layout) {
            $this->view->engine->layout('layout/' . $this->layout);
        }

        // 语言检测
        $lang = strip_tags($this->request->langset());

        $site = Config::get("site");

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        // 配置信息
        $config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'indexurl', 'cdnurl', 'version', 'timezone', 'languages'])),
            'upload'         => $upload,
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'jsname'         => 'backend/' . str_replace('.', '/', $controllername),
            'moduleurl'      => rtrim(url("/{$modulename}", '', false), '/'),
            'language'       => $lang,
            'referer'        => Session::get("referer")
        ];
        $config = array_merge($config, Config::get("view_replace_str"));

        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 配置信息后
        Hook::listen("config_init", $config);
        //加载当前控制器语言包
        $this->loadlang($controllername);
        //渲染站点配置
        $this->assign('site', $site);
        //渲染配置信息
        $this->assign('config', $config);
        //渲染权限对象
        $this->assign('auth', $this->auth);
        //渲染管理员对象
        $this->assign('admin', Session::get('admin'));
    }

    /**
     * 设置模型
     * BaseController constructor.
     * @param $model
     */
    public function setConfig($model, $table_name)
    {
        //设置模型
        $this->model = $model;
        //设置表名称
        $this->table_name = $table_name;
    }


    /**
     * 获取栏目数据
     * @param $model 模型
     * @param $table_name 表名称
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCategoryData($model, $table_name)
    {
        //设置参数
        $this->setConfig($model, $table_name);
        $ids = (int)input('param.ids');
        $this->OfficialCategoryModel = new \app\admin\model\official\OfficialCategory;
        $tree = Tree::instance();
        //->where('is_nav_show',1)->whereOr('is_flooter_nav_show',1)
        $tree->init(collection($this->OfficialCategoryModel->order('weigh desc,id desc')->field(['id,pid,name,e_name,official_rule_id,status'])->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $arr = [];
        foreach ($this->categorylist as $k => $v) {
            //设置选中
            $v['is_selected'] = 0;
            if ($ids && ($v['id'] == $ids)) {
                $v['is_selected'] = 1;
            }

            if ((($k + 1) == count($this->categorylist)) || ($this->categorylist[$k + 1]['pid'] == $v['id'])) {
                $v['is_pitch_on'] = 0;
            } else {
                $official_rule = (new \app\admin\model\official\OfficialRule())->where('id', $v['official_rule_id'])->find();
                //这一步是判断规则 规则所属表是否是当前表 状态是否是列表
                if ($official_rule && ($official_rule['table_name'] == $this->table_name) && $v['status'] == 2) {
                    $v['is_pitch_on'] = 1;
                } else {
                    $v['is_pitch_on'] = 0;
                }
            }
            $arr[] = $v;
        }
        //栏目数据
        $this->assign('category_data', $arr);
    }


    /**
     * 设置语言
     * @param $model 模型
     * @param $table_name 表名称
     */
    public function getLanguage($model, $table_name)
    {
        //设置参数
        $this->setConfig($model, $table_name);
        //语言数据
        $this->assign("languageList", $this->model->getLanguageList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //管理员测试数据
        $admin_id = $this->auth->id;
        $admin_rule = [];
        if ($admin_id != 1) {
            $addonInfo = get_addon_fullconfig('official');
            foreach ($addonInfo as $item) {
                if ($item['name'] == 'son_admin' && empty($admin_rule)) {
                    if ($item['value'] != 1) {
                        $admin_rule['admin_id'] = $admin_id;
                    }
                }
            }
        }

        //-----获取id
        $this->assignconfig('ids', (int)input('param.ids'));
        $this->assign('ids', (int)input('param.ids'));
        //—----获取路径
        $this->assignconfig('php_self', $_SERVER['PHP_SELF']);
        //获取控制器名称
        $controller_name = explode('/', trim($_SERVER['PATH_INFO'], '/'));
        $this->assignconfig('controller_name', $controller_name[0] . '/' . $controller_name[1]);
        $this->assign('controller_name', $controller_name[0] . '/' . $controller_name[1]);

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //-----获取id
            $ids = (int)input('param.ids');
            //获取语言配置项
            $language = '2';
            $official_config = (new OfficialConfig())->where('group', 'basic')->column('name,value');
            if ($official_config) {
                foreach ($official_config as $index => $value) {
                    if (isset($official_config['language_switch']) && isset($official_config['is_all_data'])) {
                        if ($official_config['is_all_data']) {
                            $language = '1,2';
                        } else {
                            $language = $official_config['language_switch'];
                        }
                    }
                }
            }

            $list = $this->model
                ->with(['official_category']);
            if ($ids) {
                $list = $list->where('official_category_id', $ids);
            }
            $list = $list
                ->where($admin_rule)
                ->where($where)
                ->whereIn('language', $language)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->auth->id;
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}